package com.frank.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.fastjson.JSON;
import com.frank.gateway.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/2/8
 * @description 自定义权限验证接口扩展
 */
@Slf4j
@Component
public class StpInterfaceImpl implements StpInterface {

    private final RedisUtil redisUtil;

    public StpInterfaceImpl(RedisUtil redisUtil) {
        log.info("我进来了");
        this.redisUtil = redisUtil;
    }

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        log.info("getPermissionList，loginId: {}, loginType: {}", loginId, loginType);
        String redisPermissionPrefixKey = "auth.permission";
        return getAuthForRedis(loginId, redisPermissionPrefixKey);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        log.info("getRoleList，loginId: {}, loginType: {}", loginId, loginType);
        // 返回此 loginId 拥有的角色列表
        String redisRolePrefixKey = "auth.role";
        return getAuthForRedis(loginId, redisRolePrefixKey);
    }

    /**
     * 从 Redis 获取权限或角色列表
     *
     * @param loginId        login id
     * @param redisPrefixKey redis key prefix
     * @return list
     */
    private List<String> getAuthForRedis(Object loginId, String redisPrefixKey) {
        String authKey = redisUtil.buildKey(redisPrefixKey, loginId.toString());
        String authValue = redisUtil.get(authKey);
        if (StringUtils.isBlank(authValue)) {
            return Collections.emptyList();
        }
        return JSON.parseArray(authValue, String.class);
    }

}